import { dataIp, temIp } from 'api/ip'
import Vue from 'vue'
import wx from 'wx'
import $ from 'jquery'
import layer from 'public/vendor/layer'
// 设置cookie
export const setCookie = function (name, value, expire) {
  var cTime = new Date().getTime()
  var eTime = cTime + expire * (24 * 60 * 60 * 1000)
  var str = name + '=' + value
  str += ';expires=' + new Date(eTime).toUTCString()
  window.document.cookie = str
}
// 获取cookie
export const getCookie = function (name = 'user[id]') {
  var json = {}
  var cookie = window.document.cookie.split('; ')
  var arr = cookie
  arr.forEach(function (item) {
    var str = item
    var arrSave = str.split('=')
    json[arrSave[0]] = arrSave[1]
  })
  if (json[name]) {
    return json[name]
  } else {
    return null
  }
}
setCookie('user[id]', '65537')
var userid = getCookie('user[id]')
// 数据请求方法
// 获取分类列表
export const GETCATELIST = function (callback) {
  return Vue.http.jsonp(dataIp + 'items/cateList', {
    callback: '?',
    headers: {hello: 'world'}
  }).then(data => {
    callback(data.data.data)
  })
}
// 获取首页推荐列表
export const GETINDEXLIST = function (callback, option) {
  var temp = {
    callback: '?'
  }
  Object.assign(temp, option)
  return Vue.http.jsonp(dataIp + 'items/indexList', temp, {
    jsonp: 'callback'
  }).then(data => {
    callback(data.data.data)
  })
}
// 获取产品列表
export const GETPRODUCTLIST = function (callback, option) {
  var temp = {
    callback: '?'
  }
  Object.assign(temp, option)
  return Vue.http.jsonp(dataIp + 'items/lists', temp, {
    jsonp: 'callback'
  }).then(data => {
    callback(data.data.data)
  })
}
// 获取首页广告
export const GETINDEXADV = function (callback, option) {
  var temp = {
    callback: '?'
  }
  Object.assign(temp, option)
  return Vue.http.jsonp(dataIp + 'Index/Ads', temp).then(data => {
    callback(data.data.data)
  })
}
// 获取用户信息
export const GETUSERINFO = function (callback, userid) {
  return Vue.http.jsonp(dataIp + 'User/get', {
    uid: userid,
    callback: '?'
  }).then(data => {
    callback(data.data.data)
  })
}
// 获取小区信息
export const GETCOMMUNITYS = function (callback, userid) {
  return Vue.http.jsonp(dataIp + 'User/com', {
    uid: userid,
    callback: '?'
  }).then(data => {
    callback(data.data.data)
  })
}
// 获取产品详情信息
export const GETPRODUCTDETAIL = function (callback, pid) {
  return Vue.http.jsonp(dataIp + 'Items/get', {
    id: pid,
    callback: '?'
  }).then(data => {
    callback(data.data.data)
  })
}
// 获取用户购物车信息
export const GETUSERCAR = function (callback, uid) {
  return Vue.http.jsonp(dataIp + 'User/countCart', {
    uid: uid,
    callback: '?'
  }).then(data => {
    callback(data.data.data)
  })
}
// 添加商品到购物车
export const ADDTOCAR = function (callback, options) {
  var temp = {}
  Object.assign(temp, options)
  // return Vue.http.jsonp(dataIp + 'Items/addCart', temp).then(data => {
  //   callback(data.data.data)
  // })
  $.ajax({
    type: 'post',
    url: dataIp + 'Items/addCart',
    data: temp,
    success: function (data) {
      if (data.status !== 0) {
        callback(data.data)
      } else {
        window.alert('提交订单失败')
      }
    }
  })
}
// 查询优惠券
export const COUPON = function (callback, options) {
  var temp = {
    callback: '?'
  }
  Object.assign(temp, options)
  return Vue.http.jsonp(dataIp + 'index/coupon', temp).then(data => {
    if (data.data.data) {
      callback(data.data.data)
    }
  })
}
// 查询积分
export const INTEGRAL = function (callback, uid) {
  return Vue.http.jsonp(dataIp + 'Jifen/jifen_items', {uid: uid}).then(data => {
    if (data.data.data) {
      callback(data.data.data)
    }
  })
}
// 查询历史兑换记录
export const INTEGRAL_HISTORY = function (callback, uid) {
  return Vue.http.jsonp(dataIp + 'Jifen/history', {uid: uid}).then(data => {
    if (data.data.data) {
      callback(data.data.data)
    }
  })
}
// 修改用户默认小区
export const changeUserCommunity = function (option, callback = () => {
}) {
  return Vue.http.jsonp(dataIp + 'life/setNowCid', option).then(data => {
    if (data.data.data) {
      callback(data.data.data)
    }
  })
}
// 获取订单、优惠券、投诉建议数量
export const ALLCOUNT = function (callback = () => {
}) {
  return Vue.http.jsonp(dataIp + 'user/countuserlist').then(data => {
    if (data.data.data) {
      callback(data.data.data)
    }
  })
}
// 获取生活服务
export const LIFESERVER = function (callback, options) {
  var temp = {
    callback: '?'
  }
  Object.assign(temp, options)
  return Vue.http.jsonp(dataIp + 'life/lifeserver', temp).then(data => {
    if (data.data.data) {
      callback(data.data.data)
    }
  })
}
// 生活服务提交
export const SAVELIFESERVER = function (options, callback = () => {
}) {
  var temp = {
    num: '1',
    oid: '12'
  }
  Object.assign(temp, options)
  $.ajax({
    type: 'post',
    url: dataIp + 'Index/order',
    data: temp,
    success: function (data) {
      if (data.data.status !== 0) {
        callback()
      } else {
        window.alert('提交订单失败')
      }
    }
  })
}
// 物流状态更改
export const DELEVERCHANGESTATUS = function (options, callback = () => {
}) {
  var temp = {}
  Object.assign(temp, options)
  $.ajax({
    type: 'post',
    url: temIp + 'Weixin/chgDelStatus',
    data: temp,
    dataType: 'jsonp',
    success: function (data) {
      if (data.data.status !== 0) {
        callback(data)
      } else {
        window.alert('操作失败')
      }
    },
    error: function () {
    }
  })
}
// 查询欠费
export const CHECKFEE = function (options, callback) {
  console.log(options)
  var temp = {}
  Object.assign(temp, options)
  return Vue.http.get(dataIp + 'Life/chaxun', temp).then(data => {
    if (data) {
      callback(data.data)
    }
  })
}
// 手机充值
export const CHARGESERVER = function (options, callback = () => {
}) {
  var temp = {}
  Object.assign(temp, options)
  $.ajax({
    type: 'post',
    url: dataIp + 'Life/recharge',
    data: temp,
    success: function (data) {
      if (data.status !== 0) {
        callback(data.data)
      } else {
        window.alert('提交订单失败')
      }
    }
  })
}
// 提交新增小区数据
export const POSTNEWAREA = function (options, callback = () => {
}) {
  var temp = {
    usertype: 1,
    uid: userid
  }
  Object.assign(temp, options)
  $.ajax({
    type: 'post',
    url: dataIp + 'User/com_update',
    data: temp,
    success: function (data) {
      if (data.status !== 0) {
        console.log(data)
        callback(data.data)
      } else {
        window.alert('新增小区失败')
      }
    }
  })
}
// 获取专题活动
export const ACTIVITY = function (callback, options) {
  var temp = {
    callback: '?'
  }
  Object.assign(temp, options)
  return Vue.http.jsonp(dataIp + 'items/topic', temp).then(data => {
    if (data.data.data) {
      callback(data.data.data)
    }
  })
}
// 获取小区列表
export const GETESTATE = function (callback) {
  return Vue.http.jsonp(dataIp + 'User/communityLists')
            .then(data => {
              return callback(data.data.data)
            })
}
// 获取楼栋列表
export const GETHOUSE = function (callback, options) {
  var temp = {
    callback: '?'
  }
  Object.assign(temp, options)
  return Vue.http.jsonp(dataIp + 'User/getLoudong', temp)
            .then(data => {
              return callback(data.data.data)
            })
}
// 获取房号列表
export const GETROOM = function (callback, options) {
  var temp = {
    callback: '?'
  }
  Object.assign(temp, options)
  return Vue.http.jsonp(dataIp + 'User/getNextRoom', temp)
            .then(data => {
              return callback(data.data.data)
            })
}
// 获取收件列表
export const RECEIVER = function (callback, options) {
  var temp = {
    callback: '?',
    uid: userid
  }
  Object.assign(temp, options)
  return Vue.http.jsonp(temIp + 'Weixin/getDelList', temp)
            .then(data => {
              return callback(data.data.data)
            })
}
export const RECEIVERDETAIL = function (callback, options) {
  var temp = {
    callback: '?'
  }
  Object.assign(temp, options)
  return Vue.http.jsonp(temIp + 'Weixin/getDetail', temp)
            .then(data => {
              console.log(data)
              return callback(data.data.data)
            })
}
// 获取收货时间列表
export const GETTIMELIST = function (callback) {
  return Vue.http.jsonp(temIp + 'Weixin/getTiming')
            .then(data => {
              return callback(data.data.data)
            })
}
// 普通方法
// 对象判空
export const isEmptyObj = function (obj) {
  if (Object.keys(obj).length === 0) {
    return true
  } else {
    return false
  }
}
// 微信接口
export const getWechatInfo = function (url, callback) {
  return Vue.http.jsonp('http://wechat.zh28.com/index.php/api/index/WechatConfig', {
    url: url,
    callback: '?'
  }).then(data => {
    callback(data.data.info)
  })
}
// 弹窗
export const qzAlert = function (title = false, content, yes = function () {
}, no = function () {
}) {
  layer.confirm(content, {
    title: title,
    skin: 'confirm',
    icon: -1,
    closeBtn: false,
    btn: ['取消', '确定']
  }, function () {
    yes()
    layer.closeAll()
  }, function () {
    no()
    layer.closeAll()
  })
}
export const qzPrompt = function (title, cont, cancle = function () {
}, callback = function () {
}) {
  layer.open({
    title: title,
    skin: 'prompt',
    content: cont,
    icon: -1,
    closeBtn: false,
    btn: ['取消', '确定'],
    yes: function (index, layero) {
      // 按钮【确定】的回调
      cancle()
      layer.closeAll()
    },
    btn2: function () {
      var times = $('.prompt input[name="time"]:checked').val()
      if (!times) {
        layer.msg('请选择送货时间！', {
          time: 1000
        })
        return false
      }
      callback(times, $('.prompt textarea').val())
    }
  })
}
// 微信基本初始化配置
export const weChat = function (options) {
  var temp = {
    debug: false,
    jsApiList: [
      'checkJsApi',
      'onMenuShareTimeline',
      'onMenuShareAppMessage',
      'onMenuShareQQ',
      'onMenuShareWeibo',
      'hideMenuItems',
      'showMenuItems',
      'hideAllNonBaseMenuItem',
      'showAllNonBaseMenuItem',
      'translateVoice',
      'startRecord',
      'stopRecord',
      'onRecordEnd',
      'playVoice',
      'pauseVoice',
      'stopVoice',
      'uploadVoice',
      'downloadVoice',
      'chooseImage',
      'previewImage',
      'uploadImage',
      'downloadImage',
      'getNetworkType',
      'openLocation',
      'getLocation',
      'hideOptionMenu',
      'showOptionMenu',
      'closeWindow',
      'scanQRCode',
      'chooseWXPay',
      'openProductSpecificView',
      'addCard',
      'chooseCard',
      'openCard'
    ],
    success: function (res) {
    }
  }
  Object.assign(temp, options)
  wx.config(temp)
}
// 微信基本分享注册
export const initWechat = function (option = {}) {
  var con = {
    title: '全众管家',
    desc: '什么才是安居乐业？全众管家为您提供一站式的管家服务！',
    link: window.location.href,
    imgUrl: 'http://www.zh28.com/data/Uploads/Item/57a456a225918.jpg',
    trigger: function (res) {
      // console.log('用户点击发送给朋友')
    },
    success: function (res) {
      // console.log('已分享')
    },
    cancel: function (res) {
      // console.log('已取消')
    },
    fail: function (res) {
      console.log(JSON.stringify(res))
    }
  }
  Object.assign(con, option)
  wx.ready(function () {
    wx.onMenuShareAppMessage(con)
    wx.onMenuShareTimeline(con)
    wx.onMenuShareQQ(con)
    wx.onMenuShareWeibo(con)
  })
}
// 获取今天时间
const GetToday = function () {
  this.now = new Date()
  this.year = this.now.getFullYear() // 返回4位数年份
  this.month = this.now.getMonth()
  this.date = this.now.getDate()
  this.hour = this.now.getHours()
  this.time = this.now.getTime()
  this.day = this.now.getDay()
}
// 获取时间列表
export const getRangeDate = function () {
  var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] // 0-11月中的日数 2月的28日由函数getDays判断是否为闰年而是否返回29
  var daysInDate = ['今天', '明天', '周日', '周一', '周二', '周三', '周四', '周五', '周六']
  var today = new GetToday()
  var month = today.month
  var day = today.day
  var date = today.date
  var arr = []
  // 月份0-11 1表示2月 判断闰年的2月日期
  function getDays (month, year) {
    if (month === 1) return ((year % 4 === 0) && ((year % 100) !== 0)) || (year % 400 === 0) ? 29 : 28
    else return daysInMonth[month]
  }

  function getRange (month, date, pm, n) {
    var totalDay = getDays(month - 1, today.year)
    var year = today.year
    var forward = daysInDate[n]
    if (n > 1) {
      var num = day + 2
      forward = daysInDate[num]
    }
    if (date > totalDay) {
      month++
      if (month > 12) {
        year = today.year + 1
        month = 1
      }
      date = date - totalDay
    }
    return {
      show: '(' + forward + ')' + month + '月' + date + '号' + pm,
      year: year,
      time: new Date(year, month - 1, date).getTime()
    }
  }

  for (var i = 0; i < 7; i++) {
    for (var k = 0; k < 2; k++) {
      var pm = k === 0 ? '上午' : '下午'
      var range = getRange(month + 1, date + i, pm, i)
      var dateItem = {}
      dateItem = {
        time: range.time,
        showDate: range.show,
        year: range.year
      }
      arr.push(dateItem)
    }
    day++
    if (day > 6) {
      day = 0
    }
  }
  if (today.hour > 11) {
    console.log(today.hour)
    arr.shift()
  }
  return arr
}
// 获取日期相差值
function getBetween (day1, day2) {
  var leave = day2 - day1
  var day = Math.floor(leave / (1000 * 60 * 60 * 24))
  var hour = Math.floor(leave / (1000 * 3600)) - (day * 24)
  var minute = Math.floor(leave / (1000 * 60)) - (day * 24 * 60) - (hour * 60)
  var second = Math.floor(leave / (1000)) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60)
  return {day, hour, minute, second}
}
// 倒计时
export const getLessData = function (start, end) {
  var startDate = parseInt(start * 1000)
  var endDate = parseInt(end * 1000)
  var currentDate = new Date().getTime()
  // var begin = getBetween(startDate, currentDate)
  var dedline = getBetween(currentDate, endDate)
  if (startDate > currentDate) {
    return '活动即将开始'
  } else if (currentDate > endDate) {
    return '已结束'
  } else {
    dedline.hour = dedline.hour < 10 ? ('0' + dedline.hour) : dedline.hour
    dedline.minute = dedline.minute < 10 ? ('0' + dedline.minute) : dedline.minute
    dedline.second = dedline.second < 10 ? ('0' + dedline.second) : dedline.second
    return dedline.day + '天 ' + dedline.hour + ':' + dedline.minute + ':' + dedline.second
  }
}

